/*
 * This file Copyright (c) 2015. Walle.
 * (http://www.wallellen.com). All rights reserved.
 *
 *
 * This file is dual-licensed under both the
 * Walle Agreement (WA) and the GNU General Public License.
 * You may elect to use one or the other of these licenses.
 *
 * This file is distributed in the hope that it will be
 * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
 * Redistribution, except as permitted by whichever of the GPL
 * or WA you select, is prohibited.
 *
 * 1. For the GPL license (GPL), you can redistribute and/or
 * modify this file under the terms of the GNU General
 * Public License, Version 3, as published by the Free Software
 * Foundation.  You should have received a copy of the GNU
 * General Public License, Version 3 along with this program;
 * if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * 2. For the Walle Agreement (WA), this file
 * and the accompanying materials are made available under the
 * terms of the WA which accompanies this distribution, and
 * is available at http://www.wallellen.com/agreement.html
 *
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 */

package com.wallellen.authority.controller;

import com.wallellen.authority.domain.Post;
import com.wallellen.authority.service.OrganizationServiceInterface;
import com.wallellen.core.page.OperateType;
import com.wallellen.core.page.RequestMode;
import com.wallellen.core.page.ViewMode;
import com.wallellen.core.sql.query.DBRule;
import com.wallellen.core.sql.query.DBSort;
import com.wallellen.core.sql.query.DataQuery;
import com.wallellen.core.sql.result.DataResult;
import com.wallellen.web.WebUtils;
import com.wallellen.web.easy.EasyUiTreeNode;
import com.wallellen.web.easy.EasyUiUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * Created by walle on 12/12/15.
 */

@RequestMapping({"/post"})
@Controller
public class PostController extends WebUtils {
    private static final Logger log = LoggerFactory.getLogger(PostController.class);
    private static final long serialVersionUID = 1L;
    @Resource
    OrganizationServiceInterface organizationServiceImpl;

    public OrganizationServiceInterface getOrganizationServiceImpl() {
        return this.organizationServiceImpl;
    }


    public void setOrganizationServiceImpl(OrganizationServiceInterface organizationServiceImpl) {
        this.organizationServiceImpl = organizationServiceImpl;
    }

    @RequestMapping({"/query"})
    @ResponseBody
    public Map<String, Object> queryall(@ModelAttribute("query") DataQuery query, HttpServletRequest request, String ids) {
        try {
            query = EasyUiUtils.formatGridQuery(request, query);
            query.addRule(new DBRule("ORGANIZATIONID", ids, "="));
            DataResult result = this.organizationServiceImpl.createPostSimpleQuery(query)
                    .search();
            result.runDictionary("0:否,1:是", "EXTENDIS");
            return ViewMode.getInstance()
                    .putAttrs(EasyUiUtils.formatGridData(result))
                    .returnObjMode();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage())
                    .returnObjMode();
        }
    }

    @RequestMapping({"/chooseUser"})
    public ModelAndView chooseUser(HttpSession session) {
        return ViewMode.getInstance()
                .returnModelAndView("authority/ChooseUserResult");
    }

    @RequestMapping({"/postActions"})
    public ModelAndView postActions(HttpSession session, String ids) {
        return ViewMode.getInstance()
                .putAttr("ids", ids)
                .returnModelAndView("authority/PostActionsSeting");
    }

    @RequestMapping({"/edit"})
    @ResponseBody
    public Map<String, Object> editSubmit(Post org, HttpSession session) {
        try {
            Post entity = this.organizationServiceImpl.editPost(org.getId(), org.getName(),
                    org.getExtendis(), getCurrentUser(session));
            return ViewMode.getInstance().setOperate(OperateType.ADD)
                    .putAttr("entity", entity).returnObjMode();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ViewMode.getInstance().setOperate(OperateType.ADD)
                    .setError(e.getMessage()).returnObjMode();
        }
    }

    @RequestMapping({"/add"})
    @ResponseBody
    public Map<String, Object> addSubmit(Post org, HttpSession session, String ids) {
        try {
            Post entity = this.organizationServiceImpl.insertPost(ids, org.getName(), org
                    .getExtendis(), getCurrentUser(session));
            return ViewMode.getInstance().setOperate(OperateType.ADD)
                    .putAttr("entity", entity).returnObjMode();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ViewMode.getInstance().setOperate(OperateType.ADD)
                    .setError(e.getMessage()).returnObjMode();
        }
    }

    @RequestMapping({"/ALONEROLEGROUP_SYSBASE_SETTREE"})
    @ResponseBody
    public ModelAndView roleGroupSetTree(String ids, String id) {
        try {
            List actions = parseIds(ids);
            this.organizationServiceImpl.setPostActionTree(actions, id);
            return ViewMode.getInstance()
                    .returnModelAndView("authority/PostActionsSeting");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ViewMode.getInstance()
                .returnModelAndView("authority/PostActionsSeting");
    }

    @RequestMapping({"/del"})
    @ResponseBody
    public ModelAndView delSubmit(String ids, HttpSession session) {
        try {
            this.organizationServiceImpl.deletePostEntity(ids,
                    getCurrentUser(session));
            return ViewMode.getInstance()
                    .returnModelAndView("authority/PostResult");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ViewMode.getInstance()
                    .setError(e.getMessage())
                    .returnModelAndView("authority/PostResult");
        }
    }

    @RequestMapping({"/ALONEMENU_RULEGROUP_TREENODE"})
    @ResponseBody
    public Object postActionsTreeInit(DataQuery query, String ids) {
        return EasyUiTreeNode.formatAjaxTree(initRoleGruopTreeNode(query, ids),
                "A_PARENTID", "A_ID", "A_NAME", "C_POSTID", "A_ICON");
    }

    private List<Map<String, Object>> initRoleGruopTreeNode(DataQuery query, String ids) {
        DataResult result = null;
        try {
            query =
                    DataQuery.init(
                            query,
                            "alone_auth_actiontree A LEFT JOIN alone_auth_action B ON A.ACTIONID = B.ID LEFT JOIN (SELECT POSTID, MENUID FROM alone_auth_postaction WHERE POSTID = '" +
                                    ids + "') C ON A.id = C.menuid",
                            "A.NAME,A.DOMAIN,a.ICON,A.ID,A.SORT,A.PARENTID,A.TREECODE,B.AUTHKEY,A.name as B_LABLE,A.TYPE,c.postid");
            query.setDistinct(true);
            query.setPagesize(100);
            query.addSort(new DBSort(" a.DOMAIN,LENGTH(A.TREECODE),a.SORT",
                    "ASC", false));
            query.setNoCount();
            result = query.search();
            for (Map node : result.getResultList())
                node.put("A_NAME", node.get("A_NAME").toString() + "&nbsp;&nbsp;&nbsp;&nbsp;<span style='color:gray;font-size:10px;'>" +
                        node.get("A_DOMAIN").toString().toUpperCase() + "</span>");
        } catch (Exception e) {
            result = DataResult.setMessager(result, e + e.getMessage());
            log.error(e.getMessage() + e);
        }
        return result.getResultList();
    }

    @RequestMapping({"/form"})
    public ModelAndView view(RequestMode pageset, String ids) {
        try {
            Post entity = null;
            switch (pageset.getOperateType()) {
                case 1:
                    return ViewMode.getInstance().putAttr("pageset", pageset)
                            .putAttr("ids", ids)
                            .returnModelAndView("authority/PostForm");
                case 0:
                    entity = this.organizationServiceImpl.getPostEntity(ids);
                    return ViewMode.getInstance().putAttr("pageset", pageset)
                            .putAttr("entity", entity)
                            .returnModelAndView("authority/PostForm");
                case 2:
                    entity = this.organizationServiceImpl.getPostEntity(ids);
                    return ViewMode.getInstance().putAttr("pageset", pageset)
                            .putAttr("entity", entity)
                            .returnModelAndView("authority/PostForm");
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e + e.getMessage())
                    .returnModelAndView("authority/OrganizationForm");
        }
        return ViewMode.getInstance().returnModelAndView("authority/OrganizationForm");
    }
}